package Listeners;

import javax.servlet.AsyncContext;
import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import java.io.IOException;

/**
 * Created by hadoop on 17-6-15.
 * NIO监听
 */
public class MyReadListener implements ReadListener {
    private ServletInputStream inputStream;
    private AsyncContext asyncContext;

    public MyReadListener(ServletInputStream inputStream, AsyncContext asyncContext) {
        this.inputStream = inputStream;
        this.asyncContext = asyncContext;
    }

    @Override
    public void onDataAvailable() throws IOException {
        System.out.println("=====数据可用=====");
        try{
            Thread.sleep(2*1000);
            StringBuilder sb = new StringBuilder();
            int len;
            byte[] buff = new  byte[1024];
            while (inputStream.isReady() && (len = inputStream.read(buff))>0){
                String data = new String(buff,0,len);
                sb.append(data);
            }
            System.out.println(sb.toString());
            asyncContext.getRequest().setAttribute("info",sb.toString());
            asyncContext.dispatch("/async.jsp");
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public void onAllDataRead() throws IOException {
        System.out.println("=====数据读取完成=====");
    }

    @Override
    public void onError(Throwable throwable) {
        throwable.printStackTrace();
    }
}
